package com.ruoyi.depot.service.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import com.ruoyi.commodity.domain.ProductImage;
import com.ruoyi.commodity.mapper.ProductImageMapper;
import com.ruoyi.common.api.localInventory.LocalInventoryApi;
import com.ruoyi.common.api.localInventory.dto.LocalInventoryDto;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.depot.domain.LocalInventoryReservedLog;
import com.ruoyi.depot.domain.vo.InventoryProductVO;
import com.ruoyi.depot.domain.vo.LocalInventoryVO;
import com.ruoyi.depot.mapper.LocalInventoryReservedLogMapper;
import com.ruoyi.depot.service.ILocalInventoryReservedLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.depot.mapper.LocalInventoryMapper;
import com.ruoyi.depot.domain.LocalInventory;
import com.ruoyi.depot.service.ILocalInventoryService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 库存Service业务层处理
 * 
 * @author luxiaoyu
 * @date 2024-12-19
 */
@Service
public class LocalInventoryServiceImpl implements ILocalInventoryService , LocalInventoryApi
{
    @Autowired
    private LocalInventoryMapper localInventoryMapper;

    @Autowired
    private ProductImageMapper productImageMapper;

    @Autowired
    private ILocalInventoryReservedLogService localInventoryReservedLogService;

    /**
     * 查询库存
     * 
     * @param inventoryId 库存主键
     * @return 库存
     */
    @Override
    public LocalInventory selectLocalInventoryByInventoryId(String inventoryId)
    {
        return localInventoryMapper.selectLocalInventoryByInventoryId(inventoryId);
    }

    /**
     * 查询库存列表
     * 
     * @param localInventory 库存
     * @return 库存
     */
    @Override
    public List<LocalInventoryVO> selectLocalInventoryList(LocalInventory localInventory)
    {
        List<LocalInventoryVO> list = localInventoryMapper.selectLocalInventoryList(localInventory);

        if(list != null && !list.isEmpty()){
            // 提取所有的产品id
            List<Long> collect = list.stream().map(LocalInventoryVO::getProductId).collect(Collectors.toList());

            // 根据产品id查询出所有的产品图片
            Map<Integer, List<String>> map = productImageMapper.selectProductImagesByProductId(collect).stream()
                    .collect(Collectors.groupingBy(
                            ProductImage::getProductId, // 按 productId 分组
                            Collectors.mapping(ProductImage::getProductImagePath, Collectors.toList()) // 提取每个 ProductImage 的图片路径并收集到 List 中
                    ));

            // 根据产品id封装对应产品的图片
            list.forEach(
                    item -> {
                        item.setProductImage(map.get(item.getProductId().intValue()));
                    }
            );
        }
        return list;
    }

    /**
     * 新增库存
     * 
     * @param localInventory 库存
     * @return 结果
     */
    @Override
    public int insertLocalInventory(LocalInventory localInventory)
    {
        return localInventoryMapper.insertLocalInventory(localInventory);
    }

    /**
     * 修改库存
     * 
     * @param localInventory 库存
     * @return 结果
     */
    @Override
    public int updateLocalInventory(LocalInventory localInventory)
    {
//        return localInventoryMapper.updateLocalInventory(localInventory);
        return 0;
    }

    /**
     * 批量删除库存
     * 
     * @param inventoryIds 需要删除的库存主键
     * @return 结果
     */
    @Override
    public int deleteLocalInventoryByInventoryIds(Long[] inventoryIds)
    {
        return localInventoryMapper.deleteLocalInventoryByInventoryIds(inventoryIds);
    }

    /**
     * 删除库存信息
     * 
     * @param inventoryId 库存主键
     * @return 结果
     */
    @Override
    public int deleteLocalInventoryByInventoryId(Long inventoryId)
    {
        return localInventoryMapper.deleteLocalInventoryByInventoryId(inventoryId);
    }

    @Override
    public List<InventoryProductVO> selectProductListByWarehouseId(InventoryProductVO vo) {
        return localInventoryMapper.selectProductListByWarehouseId(vo);
    }
    /**
     * 修改预定量/锁定量
     */
    @Override
    @Transactional
    public int updateReservedQuantity(LocalInventory localInventory) {
        LocalInventory newLIny = localInventoryMapper.selectLocalInventoryByInventoryId(localInventory.getInventoryId());
        if(newLIny == null){
            throw new ServiceException("获取产品库存信息失败，请联系管理人员核查！");
        }
        Integer oldVersion = localInventory.getVersion();
        Integer newVersion = newLIny.getVersion();
        if(oldVersion != newVersion){
            throw new ServiceException("库存数据发生变动，请刷新页面后操作！");
        }
        BigDecimal ReservedQuantity = localInventory.getReservedQuantity();
        BigDecimal AvailableQuantity = localInventory.getAvailableQuantity();
        if( ReservedQuantity.compareTo(AvailableQuantity) > 0){
            throw new ServiceException("预留量/锁定量不能超过可用量！");
        }
        //修改预定量/锁定量
        localInventoryMapper.updateReservedQuantity(localInventory);
        //新增操作日志
        LocalInventoryReservedLog log = new LocalInventoryReservedLog();
        log.setInventoryReservedLogId(IdUtils.fastSimpleUUID());
        log.setSku(localInventory.getSku());
        log.setWarehouseId(localInventory.getWarehouseId());
        log.setReservedQuantityOld(newLIny.getReservedQuantity());
        log.setReservedQuantityNew(ReservedQuantity);
        log.setCreatedTime(DateUtils.getNowDate());
        log.setCreatedBy(SecurityUtils.getNickname());

        return localInventoryReservedLogService.insertReservedLog(log);
    }
    /**
     * 根据sku和仓库id查询库存
     *
     * @param sku，warehouseId
     */
    @Override
    public LocalInventoryDto selectLocalInventoryBySkuAndWarehouseId(String sku, Long warehouseId) {
        return localInventoryMapper.selectLocalInventoryBySkuAndWarehouseId(sku, warehouseId);
    }
    /**
     * 申请退款，更新商品库存锁定
     * @return
     */
    @Override
    public int updateReservedQuantity(LocalInventoryDto localInventory) {
        LocalInventory newLIny = localInventoryMapper.selectLocalInventoryByInventoryId(localInventory.getInventoryId());
        if(newLIny == null){
            throw new ServiceException("获取产品库存信息失败，请联系管理人员核查！");
        }
        Integer oldVersion = localInventory.getVersion();
        Integer newVersion = newLIny.getVersion();
        if(oldVersion != newVersion){
            throw new ServiceException("库存数据发生变动，请刷新页面后操作！");
        }
        BigDecimal ReservedQuantity = localInventory.getReservedQuantity();
        BigDecimal AvailableQuantity = localInventory.getAvailableQuantity();
        if( ReservedQuantity.compareTo(AvailableQuantity) > 0){
            throw new ServiceException("预留量/锁定量不能超过可用量！");
        }
        LocalInventory lo = new LocalInventory();
        lo.setVersion(localInventory.getVersion());
        lo.setProductId(localInventory.getProductId());
        lo.setWarehouseId(localInventory.getWarehouseId());
        lo.setReservedQuantity(ReservedQuantity);
        //修改预定量/锁定量
        localInventoryMapper.updateReservedQuantity(lo);

        //新增操作日志
        LocalInventoryReservedLog log = new LocalInventoryReservedLog();
        log.setInventoryReservedLogId(IdUtils.fastSimpleUUID());
        log.setSku(localInventory.getSku());
        log.setWarehouseId(localInventory.getWarehouseId());
        log.setReservedQuantityOld(newLIny.getReservedQuantity());
        log.setReservedQuantityNew(ReservedQuantity);
        log.setCreatedTime(DateUtils.getNowDate());
        log.setCreatedBy(SecurityUtils.getNickname());

        return localInventoryReservedLogService.insertReservedLog(log);
    }
}
